package cluster

import (
	"fmt"
	"os"
	"path"
	"strings"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	yaml2 "sigs.k8s.io/yaml"

	"gopkg.openfuyao.cn/bkeadm/pkg/global"
	"gopkg.openfuyao.cn/bkeadm/utils/log"
)

func (op *Options) Cluster() {
	bkeCluster, err := NewBKEClusterFromFile(op.File)
	if err != nil {
		log.BKEFormat(log.ERROR, fmt.Sprintf("Failed to load the configuration file. %v", err))
		return
	}
	if len(op.NtpServer) > 0 {
		bkeCluster.Spec.ClusterConfig.Cluster.NTPServer = op.NtpServer
	}
	if !strings.HasPrefix(bkeCluster.Namespace, "bke") {
		bkeCluster.Namespace = "bke-" + bkeCluster.Namespace
	}

	by, err := yaml2.Marshal(bkeCluster)
	if err != nil {
		log.BKEFormat(log.ERROR, err.Error())
		return
	}

	_ = os.MkdirAll(path.Join(global.Workspace, "cluster"), 0644)
	bkefile := path.Join(global.Workspace, "cluster", fmt.Sprintf("%s-%s.yaml", bkeCluster.Namespace, bkeCluster.Name))
	err = os.WriteFile(bkefile, by, 0644)
	if err != nil {
		log.BKEFormat(log.ERROR, fmt.Sprintf("File generation failure %s", err.Error()))
		return
	}

	namespace := corev1.Namespace{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "v1",
			Kind:       "Namespace",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: bkeCluster.Namespace,
		},
		Spec:   corev1.NamespaceSpec{},
		Status: corev1.NamespaceStatus{},
	}

	err = global.K8s.CreateNamespace(&namespace)
	if err != nil {
		log.BKEFormat(log.WARN, err.Error())
	}

	log.BKEFormat(log.INFO, fmt.Sprintf("Submit cluster-api yaml to the cluster"))
	err = global.K8s.InstallYaml(bkefile, map[string]string{}, "")
	if err != nil {
		log.BKEFormat(log.ERROR, fmt.Sprintf("Failed to install bke-cluster, %v", err))
		return
	}
	log.BKEFormat(log.INFO, fmt.Sprintf("Submit the configuration to the cluster"))

	log.BKEFormat(log.INFO, "Waiting for the cluster to start...")
	global.K8s.WatchEventByAnnotation(bkeCluster.Namespace)
}
